from manger import scheduler
from flask import Blueprint, current_app
from views import kpl_view, position_view
import requests
import time
from views import redis_tool

my_scheduler = Blueprint('scheduler', __name__)


# 定时任务开启
@my_scheduler.route('/start')
def start():
    if not scheduler.running:
        scheduler.start()
        return {'code': 0, 'messge': 'ok'}

    else:
        return {'code': 1, 'messge': '已经在运行了'}


# 定时任务关闭
@my_scheduler.route('/stop')
def stop():
    if scheduler.running:
        scheduler.shutdown()
        return {'code': 0, 'messge': 'ok'}
    else:
        return {'code': 1, 'messge': '已经在停止了'}


@scheduler.task('cron', id='task1', day_of_week='mon-fri', hour='9-12', second='*/15')
def morningTask():
    loadZhibo()
    loadZhibo1()


@scheduler.task('cron', id='task2', day_of_week='mon-fri', hour='13-15', second='*/15')
def afternoonTask():
    loadZhibo()
    loadZhibo1()


# 更新精选候选股票池定时任务
@scheduler.task('cron', id='task3', day_of_week='mon-fri', hour=23, minute=4)
def scheduler_update_candidate_stocks():
    with scheduler.app.app_context():
        current_app.logger.info("更新全部")
        kpl_view.update_all_stocks()
        position_view.upadte_position_stocks()


# 更新当天的交易日期跟前五天的热点概念
@scheduler.task('cron', id='task4', day_of_week='mon-fri', hour=9, minute=0)
def scheduler_update_last_date():
    with scheduler.app.app_context():
        current_app.logger.info("更新当天的交易日期跟前五天的热点概念")
        kpl_view.update_redis_last()


@scheduler.task('cron', id='task5', day_of_week='mon-fri', hour=9, minute='25-59', second='*/15')
def real_morningTask1():
    with scheduler.app.app_context():
        kpl_view.montior_stock_list()
        position_view.montior_stock_list()


@scheduler.task('cron', id='task6', day_of_week='mon-fri', hour=10, second='*/15')
def real_morningTask2():
    with scheduler.app.app_context():
        kpl_view.montior_stock_list()
        position_view.montior_stock_list()


@scheduler.task('cron', id='task7', day_of_week='mon-fri', hour=11, minute='0-30', second='*/15')
def real_morningTask2():
    with scheduler.app.app_context():
        kpl_view.montior_stock_list()
        position_view.montior_stock_list()


@scheduler.task('cron', id='task8', day_of_week='mon-fri', hour='13-15', second='*/15')
def real_afternoonTask():
    with scheduler.app.app_context():
        kpl_view.gettradingcalendar()
        kpl_view.update_hots()
        kpl_view.montior_stock_list()
        position_view.montior_stock_list()

@scheduler.task('cron', id='task9', month=1,day=1, hour=0, minute=0)
def real_afternoonTask():
    with scheduler.app.app_context():
        kpl_view.updatetradingcalendar()

@scheduler.task('cron', id='task10', day_of_week='mon-fri', hour=3, minute=00)
def real_afternoonTask():
    with scheduler.app.app_context():
        redis_tool.set_login_count('0')
        
        

def loadZhibo():
    re = requests.get(
        'https://apphwhq.longhuvip.com/w1/api/index.php?PhoneOSNew=2&VerSion=5.15.0.3&a=GetPoint&apiv=w37&c=ConceptionPoint')
    result = re.json()
    with scheduler.app.app_context():
        current_app.logger.info(f"头部json{result}")
    load_hots = result['list']

    if len(load_hots) > 0:
        hot = load_hots[-1]
        hot_id = str(hot['Time'])
        hot_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(hot['Time']))

        redis_hotid = redis_tool.get_zhibokey()

        if redis_hotid != hot_id:
            redis_tool.set_zhibokey(hot_id)
            title = '关键热点'
            content = hot['Plate']
            contentStr = f"{content}\n{hot_time}"
            sound = 'bell'
            color = hot['Color']
            if color == '0':
                push = requests.get(
                    f'https://api.day.app/dRRkdzQtg23PepRjH23tkn/{title}/{contentStr}?sound={sound}')
                with scheduler.app.app_context():
                    current_app.logger.info(f"推送结果：{push.json()}")


def loadZhibo1():
    with scheduler.app.app_context():
        current_app.logger.info("获取尾部")
    re = requests.get(
        'https://apphwhq.longhuvip.com/w1/api/index.php?PhoneOSNew=2&VerSion=5.15.0.3&a=ZhiBoContent&apiv=w37&c=ConceptionPoint')
    result = re.json()
    with scheduler.app.app_context():
        current_app.logger.info(f"尾部json{result}")
    load_hots = result['List']
    if len(load_hots) > 0:
        hot = load_hots[0]
        hot_id1 = str(hot['UID'])
        hot_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(hot['Time']))
        redis_hotid1 = redis_tool.get_zhibokey1()

        if redis_hotid1 != hot_id1:
            redis_tool.set_zhibokey1(hot_id1)
            title = '开盘了'
            content = hot['Comment']
            contentstr = f"{content}\n{hot_time}"
            sound = 'bell'
            push = requests.get(f'https://api.day.app/dRRkdzQtg23PepRjH23tkn/{title}/{contentstr}?sound={sound}')
            with scheduler.app.app_context():
                current_app.logger.info(f"推送结果：{push.json()}")
